<template>
  <div class="taskDispatchEdit">
    <div class="mains_contain">
      <div class="back" @click="$router.go(-1)">
        <i class="el-icon-back"></i>
        <span>返回</span>
      </div>
      <el-form label-position="right" ref="formInline" :inline="true" :model="formInline" label-width="100px" size="small" :rules="rules">
        <el-form-item label="租户" prop="tenantId">
          <el-select v-model="formInline.tenantId" style="width: 200px" clearable placeholder="请选择" @change="onChangeTenant">
            <el-option :label="item.name" v-for="item in tenantList" :value="item.id" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="formInline.taskName" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="重发次数" prop="taskRepeatNum">
          <el-input-number v-model="formInline.taskRepeatNum" clearable :min="1" :max="10" style="width: 200px"></el-input-number>
        </el-form-item>
        <el-form-item label="任务优先级" prop="taskPriority" style="position: relative;">
          <el-input-number v-model="formInline.taskPriority" :min="1" :max="10" style="width: 200px" label="请任务优先级(数字越小优先级越高)"></el-input-number>
          <span style="margin-left: 10px; color: red;position: absolute;
    left: 0;
    bottom: -30px;">数字越小优先级越高</span>
        </el-form-item>
        <el-form-item label="任务类型" prop="taskType">
          <el-select v-model="formInline.taskType" placeholder="请选择任务类型" style="width: 200px" clearable>
            <el-option v-for="item in typeList" :label="item.label" :value="item.value" :key="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件列表" prop="taskFileIds" v-if="TOfILE.indexOf(formInline.taskType) != -1">
          <el-select v-model="formInline.taskFileIds" filterable style="width: 200px" placeholder="文件列表" @change="onChange">
            <el-option v-for="item in fileTableData" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="taskRemark">
          <el-input type="textarea" style="width: 510px" v-model="formInline.taskRemark" clearable />
        </el-form-item>
        <br />
      </el-form>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="分组列表" name="first">
          <el-table :data="groupTableData" ref="groupTable" style="width: 100%" :row-key="getKey" @select="groupSelectionChange" @select-all="groupSelectionChangeAll" @selection-change="groupChange"
            fit max-height="550" border stripe size="mini" highlight-current-row :header-cell-style="{ background: '#e5e5e5', color: '#000' }">
            <el-table-column type="selection" label="全选" width="40" :reserve-selection="true" />
            <el-table-column prop="name" label="分组名称" />
            <el-table-column prop="tenantTxt" label="租户名称" />
            <el-table-column prop="remark" label="说明" />
            <el-table-column prop="createdUserId" label="创建人">
              <template slot-scope="{ row }">
                {{ row.createBy }}
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" />
          </el-table>
          <div style="text-align: right">
            <pagination v-show="groupPagination.total > 0" :limit.sync="groupPagination.pageSize" :page.sync="groupPagination.page" :total="groupPagination.total" @pagination="getGroupList" />
          </div>
        </el-tab-pane>
        <el-tab-pane label="设备列表" name="second">
          <el-form :inline="true" :model="searchForm" size="small" label-width="100px">
            <el-form-item label="分组名称">
              <el-select v-model="searchForm.groupId" clearable placeholder="请选择分组">
                <el-option v-for="(item, index) in groupTableData" :key="index" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="设备名称">
              <el-input v-model="searchForm.name" clearable placeholder="设备名称" />
            </el-form-item>
            <!-- <el-form-item label="节点类型">
              <el-select v-model="searchForm.nodeType" clearable placeholder="请选择节点类型">
                <el-option label="终端设备" value="ENDPOINT"></el-option>
                <el-option label="网关设备" value="GATEWAY"></el-option>
                <el-option label="未知设备" value="UNKNOW"></el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" @click="deviceSearch" size="mini">查询</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="deviceTableData" ref="deviceTable" style="width: 100%" @select="deviceSelectionChange" @selection-change='deviceChange' @select-all="deviceSelectionChangeAll"
            :row-key="bindKey" fit max-height="450" border stripe size="mini" highlight-current-row :header-cell-style="{ background: '#e5e5e5', color: '#000' }">
            <el-table-column type="selection" label="全选" width="40" :reserve-selection="true" />
            <el-table-column prop="name" label="设备名称" show-overflow-tooltip />
            <el-table-column prop="nodeType" label="节点类型" width="90">
              <template slot-scope="scope">
                <span v-if="scope.row.nodeType == 'ENDPOINT'">终端设备</span>
                <span v-if="scope.row.nodeType == 'GATEWAY'">网关设备</span>
                <span v-if="scope.row.nodeType == 'UNKNOW'">未知设备</span>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip />
            <el-table-column prop="nodeId" min-width="110" label="设备唯一标识码" />
            <el-table-column prop="manufacturerId" label="产品厂商 ID" show-overflow-tooltip />
            <el-table-column prop="manufacturerName" label="产品厂商名称" show-overflow-tooltip />
            <el-table-column prop="deviceType" label="设备类型" show-overflow-tooltip />
            <el-table-column prop="model" label="型号" show-overflow-tooltip />
            <el-table-column prop="protocolType" label="协议类型" show-overflow-tooltip />
            <el-table-column prop="status" label="设备状态">
              <template slot-scope="scope">
                <span style="color: #67c23a" v-if="scope.row.status == 'ONLINE'">在线</span>
                <span style="color: #f56c6c" v-if="scope.row.status == 'OFFLINE'">离线</span>
                <span style="color: #f56c6c" v-if="scope.row.status == 'WARNING'">告警</span>
                <span style="color: #e6a23c" v-if="scope.row.status == 'INACTIVE'">未注册</span>
              </template>
            </el-table-column>
            <el-table-column prop="mute" label="设备是否冻结">
              <template slot-scope="scope">
                <span style="color: #67c23a" v-if="scope.row.mute == 'FALSE'">否</span>
                <span style="color: #f56c6c" v-if="scope.row.mute == 'TRUE'">是</span>
              </template>
            </el-table-column>
          </el-table>
          <div style="text-align: right">
            <pagination v-show="devicePagination.total > 0" :limit.sync="devicePagination.pageSize" :page.sync="devicePagination.page" :total="devicePagination.total" @pagination="getDeviceList" />
          </div>
        </el-tab-pane>
      </el-tabs>
      <div>
        <el-button type="primary" size="small" @click="onSubmit('formInline')">保存</el-button>
        <el-button size="small" @click="onCanle">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import * as api from "@/api/link/file";
import * as deviceApi from "@/api/link/device";
import * as dispatchApi from "@/api/link/dispatch";
import * as deviceGroup from "@/api/link/deviceGroup";
import * as taskApi from "@/api/link/task";
import * as tenantApi from "@/api/sys/tenant";

export default {
  comments: {},
  props: {},
  data() {
    let account = /^[\u4e00-\u9fa5a-zA-Z-z0-9]+$/;
    const validateName = (rule, value, callback) => {
      if (value == "" || !value) {
        callback(new Error("请输入任务名称"));
      } else {
        if (account.test(value)) {
          callback();
        } else {
          callback(new Error("任务名称不能出现特殊字符"));
        }
      }
    };
    return {
      tenantList: [],
      TOfILE: ["CfgfileLoad", "ShellScriptLoad", "SoftwareLoad", "PatchLoad"],
      formInline: {
        taskFileIds: "",
        taskPriority: 1,
      },
      multipleFile: [],
      multipleGroup: [],
      multipleDevice: [],
      fileTableData: [], //文件table
      groupTableData: [], //分组table
      deviceTableData: [], //设备table
      tableSelectList: [],
      rules: {
        taskName: [
          {
            min: 2,
            max: 15,
            message: "长度在 2 到 15 个字符",
            trigger: "blur",
          },
          { required: true, trigger: "blur", validator: validateName },
        ],
        taskType: [
          { required: true, message: "必须选择任务类型", trigger: "change" },
        ],
        taskPriority: [
          { required: true, message: "必须输入任务优先级", trigger: "blur" },
        ],
        taskFileIds: [
          { required: true, message: "必须选择文件", trigger: "change" },
        ],
        tenantId: [
          { required: true, message: "必须选择租户", trigger: "change" },
        ],
      },
      pagination: {
        total: 1,
        page: 1,
        pageSize: 100,
      },
      groupPagination: {
        total: 1,
        page: 1,
        pageSize: 10,
      },
      devicePagination: {
        total: 1,
        page: 1,
        pageSize: 10,
      },
      activeName: "second",
      username: localStorage.getItem("username"),
      typeList: [
        // { value: 1, label: "获取设备信息" },
        // { value: 2, label: "系统文件下载" },
        // { value: 3, label: "系统文件下载状态查询" },
        // { value: 'DeviceState', label: "获取设备信息" },
        { value: "SoftwareLoad", label: "设备升级" },
        { value: "PatchLoad", label: "补丁升级" },
        // { value: 'SoftwareLoadStatus', label: "系统文件下载状态查询" },
        // { value: 'CfgfileLoad', label: "配置文件升级" },
        // { value: 'CfgfileLoadStatus', label: "配置文件升级状态查询" },
        // { value: 'SystemReboot', label: "重启设备" },
        // { value: 'LogfileUpload', label: "设备日志收集" },
        // { value: 'LogfileUploadNotify', label: "设备日志收集结果上报" },
        // { value: 'LogfileUploadStatus', label: "设备日志收集状态查询" },
        // { value: 'ShellScriptLoad', label: "应用升级" },
        // { value: 'ShellScriptLoadNotify', label: "可执行文件执行结果上报" },
        // { value: 'ShellScriptLoadStatus', label: "可执行文件执行状态查询" },
        // { value: 'EthStatus', label: "网络接口信息查询" },
      ],
      searchForm: {
        groupId: null,
        nodeType: 'GATEWAY'
      },
      flags: false,
      currentPageNodeIdList: [],
      currentPageClientIdList: [],
      deleteNodeIdList: [],
      deleteClientIdList: [],
      isTriggerTableChange: false,
      nowIndex: ''
    };
  },
  computed: {
    maxHeight() {
      var curHeight =
        window.innerHeight ||
        document.documentElement.clientHeight ||
        document.body.clientHeight;
      return curHeight - 280;
    },
  },
  created() { },
  mounted() {
    //
    // var curRow = Object.assign(this.$route.query)
    // this.formInline = curRow
    this.initList();
    this.search();
    this.getTenantList();
  },
  methods: {
    bindKey(row) {
      return row.deviceId;
    },
    getKey(row) {
      return row.id;
    },
    initList() {
      taskApi.getById(this.$route.query.id).then((res) => {
        
        this.formInline = res.data;
        this.getProupPage();
        this.getDeviceList();
      });
    },
    onChangeTenant(val) {
      //
      this.getProupPage();
      this.getDeviceList();
    },
    // 获取租户数据
    getTenantList() {
      tenantApi.queryIdNamePair().then((res) => {
        this.tenantList = res.data;
      });
    },
    handleClick(tab, event) {
      if (tab.index == "0") {
        // this.$refs.deviceTable.clearSelection();
      } else if (tab.index == "1") {
      }
    },
    // 获取分组
    getProupPage() {
      const p = Object.assign({}, this.groupPagination, {
        tenantId: this.formInline.tenantId,
      });
      deviceGroup.page(p).then((resp) => {
        this.groupTableData = resp.data.list;
        this.groupPagination = resp.data.pagination;
        this.groupPagination.page = resp.data.pagination.current;
        this.groupTableData.forEach((val) => {
          if (this.formInline.groupIdList.indexOf(val.id) > -1) {
            this.$refs.groupTable.toggleRowSelection(val);
            // this.multipleGroup.push(val)
          }
        });
        return
        if (this.formInline.groupIdList.length) {
          this.$nextTick(() => {
            this.formInline.groupIdList.forEach((val, index) => {
              let obj = this.groupTableData.find((o) => o.id == val);
              if (obj) this.$refs.groupTable.toggleRowSelection(obj);
              this.multipleGroup.push(obj)
            });
          });
        }
      });
    },
    getDeviceList(val) {
      
      // this.currentPageNodeIdList = [];
      // this.currentPageClientIdList = [];
      // this.isTriggerTableChange = false;
      this.$refs.deviceTable.clearSelection();
      const p = Object.assign(
        {},
        this.devicePagination,
        {
          tenantId: this.formInline.tenantId,
        },
        this.searchForm
      );
      deviceApi.page(p).then((resp) => {
        
        this.deviceTableData = resp.data.list;
        this.devicePagination = resp.data.pagination;
        this.devicePagination.page = resp.data.pagination.current;
        // this.multipleDevice = []
        this.deviceTableData.forEach((val) => {
          if (this.formInline.deviceNodeIdList.indexOf(val.nodeId) > -1) {
            // this.nowIndex = this.devicePagination.page
            // 
            this.$refs.deviceTable.toggleRowSelection(val);
          }
        });
        
        
      });
    },
    onChange(value) {
      var list = [2, 3, 4, 5];
      if (list.indexOf(value) != -1) {
        // 文件
      } else {
      }
    },
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var sendCommandDTO = null;
          var sendCommandDTO1 = null;
          
          
          if (!this.formInline.groupIdList.length && !this.formInline.deviceNodeIdList.length) {
            this.$message({
              message: "请选择分组或者选择设备！！！",
              type: "error",
            });
            return;
          }
          sendCommandDTO = {
            groupIdList:this.formInline.groupIdList,
            taskType: this.formInline.taskType,
            taskFileIds: this.formInline.taskFileIds,
            tenantId: this.formInline.tenantId,
          };
          // this.multipleGroup.map((item) => {
          //   sendCommandDTO.groupIdList.push(item.id);
          // });
          sendCommandDTO1 = {
            deviceClientIdList: this.formInline.deviceClientIdList,
            deviceNodeIdList: this.formInline.deviceNodeIdList,
            taskType: this.formInline.taskType,
            taskFileIds: this.formInline.taskFileIds,
            tenantId: this.formInline.tenantId,
          };
          this.formInline.groupIdList = sendCommandDTO.groupIdList;
          var p = Object.assign(
            sendCommandDTO,
            sendCommandDTO1,
            this.formInline
          );
          p.taskName = p.taskName.replace(/\s*/g, ""); // 去除任务名称中的空格
          //
          taskApi.update(p).then((resp) => {
            if (resp.code == 200) {
              this.$message({
                message: "保存成功！！！",
                type: "success",
              });
              this.$router.push({
                path: "/taskList",
              });
            } else {
              this.$message.error("保存失败！！！");
            }
          });
        } else {
          return false;
        }
      });
    },
    onCanle() {
      this.$router.push({
        path: "/taskList",
        query: this.$route.query,
      });
    },
    deviceSearch() {
      this.getDeviceList()
    },
    groupSelectionChangeAll(list) {
      list && list.map(item => {
        let index = this.formInline.groupIdList.indexOf(item.id)
        if (index < 0) {
          this.formInline.groupIdList.push(item.id)
        }
      })
      if (!list.length) {
        this.formInline.groupIdList = this.formInline.groupIdList.splice(0, this.formInline.groupIdList.length - 10)
      }
    },
    groupChange(list) {
      if (list.length) {
        list.map(item => {
          let index = this.formInline.groupIdList.indexOf(item.id)
          if (index > -1) {
            this.formInline.groupIdList.splice(index, 1)
          }
          this.formInline.groupIdList.push(item.id)
        })
      }

    },
    // 分组复选框事件
    groupSelectionChange(list, val) {
      if (list.includes(val)) {
        list.map(item => {
          let index = this.formInline.groupIdList.indexOf(item.id)
          if (index < 0) {
            this.formInline.groupIdList.push(item.id)
          }
        })
      } else {
        let i = this.formInline.groupIdList.indexOf(val.id)
        
        if (i > -1) {
          this.formInline.groupIdList.splice(i, 1)
        } else {
          list && list.map(item => {
            let indexs = this.formInline.groupIdList.indexOf(item.id)
            if (indexs < 0) {
              this.formInline.groupIdList.push(item.id)
            }
          })
        }

      }

      // var obj = {};
      // val = val.reduce(function (item, next) {
      //   obj[next.id] ? "" : (obj[next.id] = true && item.push(next));
      //   return item;
      // }, []);
      // if (val) {
      //   this.multipleGroup = val;
      // } else {
      //   this.multipleGroup = []
      // }
      // // this.multipleGroup = val;
      // //
    },
    deviceSelectionChangeAll(list) {
      
      list && list.map(item => {
        let index = this.formInline.deviceNodeIdList.indexOf(item.nodeId)
        if (index < 0) {
          this.formInline.deviceNodeIdList.push(item.nodeId)
          this.formInline.deviceClientIdList.push(item.deviceId)
        }
      })
      if (!list.length) {
        this.formInline.deviceNodeIdList = this.formInline.deviceNodeIdList.splice(0, this.formInline.deviceNodeIdList.length - 10)
        this.formInline.deviceClientIdList = this.formInline.deviceClientIdList.splice(0, this.formInline.deviceClientIdList.length - 10)
      }
      
      

    },
    deviceChange(list) {
      
      if (list.length) {
        list.map(item => {
          let index = this.formInline.deviceNodeIdList.indexOf(item.nodeId)
          if (index > -1) {
            this.formInline.deviceNodeIdList.splice(index, 1)
            this.formInline.deviceClientIdList.splice(index, 1)
          }
          this.formInline.deviceNodeIdList.push(item.nodeId)
          this.formInline.deviceClientIdList.push(item.deviceId)
        })
      }
      
      
    },
    // 设备复选框事件
    deviceSelectionChange(list, val) {
      if (list.includes(val)) {
        list.map(item => {
          let index = this.formInline.deviceNodeIdList.indexOf(item.nodeId)
          if (index < 0) {
            this.formInline.deviceNodeIdList.push(item.nodeId)
            this.formInline.deviceClientIdList.push(item.deviceId)
          }
        })
      } else {
        let i = this.formInline.deviceNodeIdList.indexOf(val.nodeId)
        
        if (i > -1) {
          this.formInline.deviceNodeIdList.splice(i, 1)
          this.formInline.deviceClientIdList.splice(i, 1)
        } else {
          list && list.map(item => {
            let indexs = this.formInline.deviceNodeIdList.indexOf(item.nodeId)
            if (indexs < 0) {
              this.formInline.deviceNodeIdList.push(item.nodeId)
              this.formInline.deviceClientIdList.push(item.deviceId)
            }
          })
        }

      }
      
      
      return
      this.tableSelectList[this.nowIndex] = val;
      
      if (val && val.length) {
        val.map(item => {

          
          let index = this.formInline.deviceNodeIdList.indexOf(item.nodeId)
          
          if (index > -1) {
            this.formInline.deviceNodeIdList.splice(index, 1)
            // this.formInline.deviceNodeIdList.push(item.nodeId)
            
          }
          this.formInline.deviceNodeIdList.push(item.nodeId)
          
        })
      } else {
        

      }
      return
      if (val && val.length) {
        let arr = this.tableSelectList.flat();
        
        if (this.nowIndex) {
          this.formInline.deviceNodeIdList.forEach(res => {
            val.forEach(item => {
              if (res == item.nodeId) {
                let indexs = this.formInline.deviceNodeIdList.indexOf(res) //索引
                let a = this.tableSelectList[this.nowIndex].findIndex(re => {
                  return re.nodeId == res
                })
                if (a > -1) {

                } else {
                  this.formInline.deviceNodeIdList.splice(indexs, 1)
                }
                

              } else {
                arr.map(item => {
                  if (this.formInline.deviceNodeIdList.indexOf(item.nodeId) < 0) {
                    this.formInline.deviceNodeIdList.push(item.nodeId)
                  }
                })
              }
            })
          })
        }



      }
      


      // 
      return

      if (!this.isTriggerTableChange) {
        return;
      }
      //
      let addNodeIdList = [];
      let addClientIdList = [];
      if (val.length) {
        let deleteNodeIdList = Object.assign([], this.deleteNodeIdList);
        let deleteClientIdList = Object.assign([], this.deleteClientIdList);


        val && val.forEach((item) => {
          addNodeIdList.push(item.nodeId);
          addClientIdList.push(item.deviceId);
        });

        this.deleteNodeIdList.forEach((item) => {
          val && val.forEach((selectItem) => {
            if (item == selectItem.nodeId) {
              const index1 = deleteNodeIdList.indexOf(item);
              deleteNodeIdList.splice(index1, 1);
              deleteClientIdList.splice(index1, 1);
              const index2 = addNodeIdList.indexOf(item);
              addNodeIdList.splice(index2, 1);
              addClientIdList.splice(index2, 1);
            }
          });
        });

        deleteNodeIdList.forEach((item) => {
          const indexDelete = this.deleteNodeIdList.indexOf(item);
          this.deleteNodeIdList.splice(indexDelete, 1);
          this.deleteClientIdList.splice(indexDelete, 1);
          const index = this.formInline.deviceNodeIdList.indexOf(item);
          this.formInline.deviceNodeIdList.splice(index, 1);
          this.formInline.deviceClientIdList.splice(index, 1);
        });

        addNodeIdList.forEach((item) => {
          this.deleteNodeIdList.push(item);
          this.formInline.deviceNodeIdList.push(item);
        });
        addClientIdList.forEach((item) => {
          this.deleteClientIdList.push(item);
          this.formInline.deviceClientIdList.push(item);
        });

        this.formInline.deviceNodeIdList.forEach((item, index) => {
          this.multipleDevice.push(item);
        });
      } else {
        
        this.multipleDevice = []
        this.formInline.deviceNodeIdList = []
        this.formInline.deviceClientIdList = []
      }
    },
    tableDefaultSelect() {
      
      let rows = [];     //先定义一个选中行的数组
      if (JSON.stringify(this.tableSelectList) !== '[]') {
        let arr = this.tableSelectList.flat();
        
        for (let i in arr) {
          if (this.deviceTableData.findIndex(x => x.id === arr[i].id) >= 0) {
            rows.push(this.deviceTableData.findIndex(x => x.id === arr[i].id));
          }
        }
        this.$nextTick(() => {    //等dom更新之后再选中，并且表格一定要设置ref
          if (rows) {
            rows.forEach(row => {
              this.$refs.deviceTable.toggleRowSelection(this.deviceTableData[row]);
            })
          }
        });
      }
    },
    // 分组分页查询
    getGroupList() {
      this.getProupPage();
    },
    search() {
      const p = Object.assign({}, this.pagination);
      api.page(p).then((resp) => {
        this.fileTableData = resp.data.list;
        this.pagination = resp.data.pagination;
        this.pagination.page = resp.data.pagination.current;
      });
    },
  },
  watch: {

  },
};
</script>

<style scoped lang="scss">
.taskDispatchEdit {
  padding: 20px;

  .curHeader {
    position: relative;
    height: 40px;
    .searcherBox {
      position: absolute;
      right: 0;
      top: 0;
    }
  }
  ::v-deep.el-form-item {
    margin-bottom: 24px;
  }
}
</style>
